<template>
  <div class="video-container">
    <div class="video-left-board">
      <div class="video-left-board-top">
        <div style="padding-top: 2px;padding-left:5px;">
          <el-input
            v-model="queryParams.vehicleId"
            placeholder="可查询车辆标识"
            clearable
            style="width: 77%;"
            @clear="handleQuery"/>
          <el-button  style="" icon="el-icon-search"  @click="handleQuery"></el-button>
        </div>
      </div>
      <div class="video-left-board-center">
        <el-tree
          ref="myTree"
          :data="treeData"
          :props="props"
          node-key="id"
          :highlight-current="true"
          :load="loadNode"
          :render-content="renderContent"
          lazy
          @node-click="handleNodeClick">
        </el-tree>
      </div>
    </div>

    <div class="video-center-board">
      <div class="video-center-board-top">
        <div class="video-center-board-top-div">
          <div style="float: left;margin-top:3px;margin-left:10px">
            <el-form :model="historyVedioQueryParams" ref="queryForm" size="small" :inline="true" >
              <el-form-item label="历史录像时间" prop="daterangeDate">
                <el-date-picker
                  v-model="daterangeDate"
                  value-format="yyyyMMddHHmmss"
                  type="datetimerange"
                  range-separator="-"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  :picker-options="pickerOptions"
                  clearable
                ></el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="historyVedioQuery">查询视频</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div :class="{ videoCenterBoardDown: isFullscreen }" style="overflow: hidden;position: relative;
                height: calc(100vh - 126px);background: #fff;box-sizing: border-box;">
        <div style="width: 100%;height: 100%;" class="my-video-wrapper" >
          <div class="player-wraper" >
            <div style="width: 100%;height: 100%;" id="video" ></div>
          </div>
          <div class="my-video-control">
            <div class="device-states">
              <span id="video-span"></span>
            </div>
            <div class="video-controls">
              <span>
                <svg-icon :icon-class="isVideoPlay?'video-pause':'video-play'" @click="playControl()"/>
              </span>
              <span>
                 <svg-icon icon-class="video-play-stop"  @click="playStop()"/>
              </span>
              <span>
                <svg-icon :icon-class="isVideoVoice?'video-voice-close':'video-voice-open'" @click="videoVoice()"/>
              </span>
              <span>
                <svg-icon icon-class="video-photo" @click="videoPhoto()"/>
              </span>
              <span>
                <svg-icon :icon-class="isFullscreen?'video-full-screen-cancel':'video-full-screen'" @click="videoFullScreen()"/>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="video-right-board">
      <el-table  :data="historyVideoList" >
        <el-table-column label="开始时间" width="120" align="center" prop="beginTimeFormat" />
        <el-table-column label="结束时间" width="120" align="center" prop="endTimeFormat" />
        <el-table-column label="操作" width="60" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              title="播放"
              size="medium"
              type="text"
              icon="el-icon-video-play"
              @click="historyVedioPlay(scope.row)"/>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>

import {getCarDevTree, getCarDevTreeByVehicleId} from "@/api/buss/realTimeVedio";
import screenfull from "screenfull";
import $ from "jquery";
import {FLVPlayer, historyVedioControl, historyVedioPlay, historyVedioQuery} from "@/api/buss/historyVedio";
import moment from "moment";

export default {
  name: "HistoryVedio",
  components: {
  },
  computed: {
    // 默认时间
    dateDefault() {
      let date1 = moment().subtract(1, "hours").format("YYYYMMDDHHmmss");
      let date2 = moment().format("YYYYMMDDHHmmss");
      // 通过时间戳计算
      return [date1, date2]
    }
  },
  data() {
    return {
      // 车辆设备树
      props: {
        id: 'id',
        carDevId: 'carDevId',
        label: 'label',
        carDevStatus: 'carDevStatus',
        whetherCompanyNode: 'whetherCompanyNode',
        whetherCarDevNode: 'whetherCarDevNode',
        whetherCarDevChnNode: 'whetherCarDevChnNode',
        isLeaf: 'whetherLastLevelNode'
      },
      videoPlayer: null,//FLVPlayer
      historyVideoList: [],// 历史视频表格数据
      selectCarDevId: null,//选择的车辆设备id
      selectCarDevChn: null,//选择的视频通道
      propParams: {//查询车辆设备树结构参数
        id: null,
        yesNotCarDevNode: null
      },
      queryParams: {//根据车辆标识查询车辆树参数
        vehicleId: null
      },
      historyVedioQueryParams: {//根据时间查询历史视频列表参数
        selectCarDevId: null,
        selectCarDevChn: null,
        startTime: null,
        endTime: null
      },
      historyVedioPlayParams: {//历史视频播放参数
        phone: null,
        videoChn: null,
        beginTime: null,
        endTime: null
      },
      historyVedioPlayControlParams: {//历史视频播放控制参数
        phone: null,
        videoChn: null,
        ctrlCmd: null,//控制指令
        multiples: null,//快进或快退倍数
        replayLocation: null,//拖动回放位置
        beginTime: null,
        endTime: null
      },
      daterangeDate: [],//时间范围
      historyVedioPhone: null,//播放的视频手机号
      historyVedioVideoChn: null,//播放的视频通道
      isFullscreen: false,//是否全屏
      isVideoPlay: false,//视频是否播放
      isVideoVoice: false,//视频是否静音
      videoMap: new Map(), // 视频map，key-video固定值，value-FLVPlayer
      pickerOptions: {
        shortcuts: [{
          text: '最近一小时',
          onClick(picker) {
            const end = moment(new Date()).format("YYYYMMDDHHmmss");
            const start = moment(new Date()).subtract(1, "hours").format("YYYYMMDDHHmmss");
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三小时',
          onClick(picker) {
            const end = moment(new Date()).format("YYYYMMDDHHmmss");
            const start = moment(new Date()).subtract(3, "hours").format("YYYYMMDDHHmmss");
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '今天',
          onClick(picker) {
            const date = moment().format("YYYYMMDD");
            const end = date + '235959';
            const start = date + '000000';
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = moment().subtract(1, "days").format("YYYYMMDD").trim();
            const end = date + '235959';
            const start = date + '000000';
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      renderContent(h, { node, data }) {
        if(data.whetherCarDevNode){
          if("01" === data.carDevStatus){
            return (
              <span>
              <svg-icon icon-class="car-online"/>
              <span style="margin-left:3px">{node.label}</span>
            </span>);
          }else {
            return (
              <span>
              <svg-icon icon-class="car-offline"/>
              <span style="margin-left:3px">{node.label}</span>
            </span>);
          }
        }else if(data.whetherCarDevChnNode){
          if("01" === data.carDevStatus){
            return (
              <span>
              <svg-icon icon-class="video-onlile"/>
              <span style="margin-left:3px">{node.label}</span>
            </span>);
          }else {
            return (
              <span>
              <svg-icon icon-class="video-offlile"/>
              <span style="margin-left:3px">{node.label}</span>
            </span>);
          }
        }else {
          return (
            <span>
              <i class={node.icon}/>
              <span>{node.label}</span>
            </span>);
        }
      },
      treeData: []//车辆树数据
    }
  },
  watch: {
  },
  created() {
  },
  methods: {
    loadNode(node, resolve) {
      if (node === null || node === undefined || node.level === 0){
        this.propParams.id = null;
        this.propParams.whetherCarDevNode = false;
        getCarDevTree(this.propParams).then(response => {
          this.treeData = response.data;
        });
      }else{
        if (node.data.isLeaf === true){
          return resolve([]);
        }
        this.propParams.id = node.data.id;
        this.propParams.whetherCarDevNode = node.data.whetherCarDevNode;
        this.propParams.whetherCompanyNode = node.data.whetherCompanyNode;

        getCarDevTree(this.propParams).then(response => {
          if(node.data.whetherCompanyNode){
            var label  = node.data.label;
            var label1 = label.split("(")[0];
            var label2 = response.data[0].onlineStatusCount;
            node.data.label = label1+label2;
          }
          return resolve(response.data);
        });
      }
    },
    handleQuery() {//根据车辆标识查询车辆树
      if(this.queryParams.vehicleId === null || this.queryParams.vehicleId === ''|| this.queryParams.vehicleId.trim() === ''){
        this.loadNode();
      }else {
        getCarDevTreeByVehicleId(this.queryParams).then(response => {
          this.treeData = response.data;
        });
      }
    },
    historyVedioQuery: function() {//历史视频列表查询
      if(this.selectCarDevId == null || this.selectCarDevChn == null){
        this.$message({
          message: '请选择车辆设备的视频通道',
          type: 'warning'
        });
        return;
      }

      this.historyVedioQueryParams.startTime = null;
      this.historyVedioQueryParams.endTime = null;
      this.historyVedioQueryParams.selectCarDevId = this.selectCarDevId;
      this.historyVedioQueryParams.selectCarDevChn = this.selectCarDevChn;
      if (null != this.daterangeDate && '' !== this.daterangeDate && 0 !== this.daterangeDate.length) {
        this.historyVedioQueryParams.startTime = this.daterangeDate[0];
        this.historyVedioQueryParams.endTime = this.daterangeDate[1];
      }else {
        this.$message({
          message: '历史录像时间不能为空！',
          type: 'warning'
        });
        return false;
      }

      historyVedioQuery(this.historyVedioQueryParams).then(response => {
          const responseData = response.data;
          if(responseData != null){
            const num = responseData.videoNum;
            if(num === 0){
              this.$message({
                message: '该时间段内没有历史视频',
                type: 'warning'
              });
            }else {
              this.historyVideoList = responseData.videoList;
            }
          }else {
            this.$message({
              message: '未获取到历史视频',
              type: 'warning'
            });
          }
      });
    },
    resetQuery() {
      this.daterangeDate = this.dateDefault;
      this.resetForm("queryForm");
    },
    // 节点单击事件
    handleNodeClick(data) {
      const tree = this.$refs.myTree;
      if(data.whetherCarDevChnNode){
        if("01" === data.carDevStatus){
          this.selectCarDevId = data.carDevId;
          this.selectCarDevChn = data.id;
          if (tree) {
            tree.setCurrentKey(data.id);
          }
        }else {
          tree.setCurrentKey(null);
          this.$message({
            message: '该设备未在线',
            type: 'warning'
          });
          this.selectCarDevId = null;
          this.selectCarDevChn = null;
        }
      }else {
        tree.setCurrentKey(null);
        this.selectCarDevId = null;
        this.selectCarDevChn = null;
      }
    },
    /** 历史视频播放按钮操作 */
    historyVedioPlay(row) {
      this.historyVedioPlayParams.phone = row.phone;
      this.historyVedioPlayParams.beginTime = row.beginTime;
      this.historyVedioPlayParams.endTime = row.endTime;
      this.historyVedioPlayParams.videoChn = row.logicalChn;
      if(this.videoPlayer != null){
        this.historyVedioPlayControlParams.phone = row.phone;
        this.historyVedioPlayControlParams.videoChn = row.logicalChn;
        this.historyVedioPlayControlParams.ctrlCmd = 2;
        this.historyVedioControlFunction(this.historyVedioPlayControlParams);
        this.videoPlayer.destroy();//先销毁之前的
        this.videoPlayer = null;
        $("#video").empty();
        $("#video-span").empty();
        this.isVideoPlay = false;
        // 使用 setTimeout 来暂停几秒
        setTimeout(() => {
          // 这里是延迟后要执行的代码
          this.historyVedioPlayFunction();
        }, 1000); // 暂停1秒钟（1000毫秒）
      }else {
        this.historyVedioPlayFunction();
      }
    },
    historyVedioPlayFunction(){//历史视频播放
      historyVedioPlay(this.historyVedioPlayParams).then(response => {
        this.historyVedioPhone = this.historyVedioPlayParams.phone;
        this.historyVedioVideoChn = this.historyVedioPlayParams.videoChn;
        const responseData = response.data;
        this.videoPlayer = new FLVPlayer({
          container: $('#video'),
          url:responseData.playUrl,
          // 自动快进追祯，但是可能会导致画面停顿
          autoFastForward: false,
        });
        this.videoPlayer.play();
        this.isVideoPlay = true;
        $("#video-span").html(responseData.vehicleId+"-"+responseData.logicalChn);
      });
    },
    historyVedioControlFunction(historyVedioPlayParams) {//向终端下发远程录像回放控制
      historyVedioControl(historyVedioPlayParams).then(response => {
        const responseData = response.data;
      });
    },
    screenfullChange() {
      this.isFullscreen = screenfull.isFullscreen;
    },
    screenfullInit() {
      if (screenfull.isEnabled) {
        screenfull.on('change', this.screenfullChange)
      }
    },
    screenfullDestroy() {
      if (screenfull.isEnabled) {
        screenfull.off('change', this.screenfullChange)
      }
    },
    //播放控制
    playControl(){
      if(this.videoPlayer != null){
        if(this.isVideoPlay){
          const parentElement = document.getElementById('video');
          if (parentElement.children && parentElement.children.length > 0) {
            const firstChild = parentElement.children[0];
            firstChild.pause();
          }
          this.isVideoPlay = !this.isVideoPlay;
        }else {
          const parentElement = document.getElementById('video');
          if (parentElement.children && parentElement.children.length > 0) {
            const firstChild = parentElement.children[0];
            firstChild.play();
          }
          this.isVideoPlay = !this.isVideoPlay;
        }
      }
    },
    //停止播放
    playStop(){
      if(this.videoPlayer != null){
        this.historyVedioPlayControlParams.phone = this.historyVedioPlayParams.phone;
        this.historyVedioPlayControlParams.videoChn = this.historyVedioPlayParams.videoChn;
        this.historyVedioPlayControlParams.ctrlCmd = 2;
        this.historyVedioControlFunction(this.historyVedioPlayControlParams);
        this.videoPlayer.destroy();
        this.videoPlayer = null;
        this.historyVedioPhone = null;
        this.historyVedioVideoChn = null;
        $("#video").empty();
        $("#video-span").empty();
        this.isVideoPlay = false;
      }
    },
    //声音控制
    videoVoice(){
      const parentElement = document.getElementById('video');
      if (parentElement.children && parentElement.children.length > 0) {
        const firstChild = parentElement.children[0];
        if (firstChild.muted) {
          firstChild.muted = false;
          this.isVideoVoice = false;
        } else {
          firstChild.muted = true;
          this.isVideoVoice = true;
        }
      }
    },
    //截图保存
    videoPhoto() {
      const parentElement = document.getElementById('video');
      if (parentElement.children && parentElement.children.length > 0) {
        const firstChild = parentElement.children[0];
        const canvas = document.createElement('canvas');
        canvas.width = firstChild.videoWidth;
        canvas.height = firstChild.videoHeight;
        canvas.getContext('2d').drawImage(firstChild, 0, 0, canvas.width, canvas.height);

        canvas.toBlob((blob) => {
          if (blob) {
            // 创建一个URL指向blob对象
            const url = URL.createObjectURL(blob);
            // 创建一个a标签用于下载
            const link = document.createElement('a');
            link.href = url;
            link.download = 'screenshot.png';
            link.click();
            // 清除URL对象
            URL.revokeObjectURL(url);
          }
        }, 'image/png');
      }
    },
    //视频全屏
    videoFullScreen() {
      const parentElement = document.getElementById('video');
      if (parentElement.children && parentElement.children.length > 0) {
        const firstChild = parentElement.children[0];
        if (firstChild.requestFullscreen) {
          firstChild.requestFullscreen();
        } else if (firstChild.mozRequestFullScreen) { // Firefox
          firstChild.mozRequestFullScreen();
        } else if (firstChild.webkitRequestFullscreen) { // Chrome, Safari and Opera
          firstChild.webkitRequestFullscreen();
        } else if (firstChild.msRequestFullscreen) { // IE/Edge
          firstChild.msRequestFullscreen();
        }
      }
    }
  }
}
</script>

<style lang='scss' scoped>

//.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
//  margin-bottom: 10px;
//}
.cell .el-button--medium{
  padding: 0;
  font-size: 20px;
}
.my-video-control{
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 35px;
  background-color: #000;
  color: #fff;
}
.my-video-control .device-states{
  float: left;
  height: 35px;
  line-height: 35px;
  padding-left: 5px;
  position: absolute;
  left: 0;
  top: 0;
  font-size: 12px;
  color: #c1c2c6;
}
.my-video-control .video-controls{
  height: 35px;
  line-height: 35px;
  font-size: 20px;
  position: absolute;
  right: 0;
  top: 0;
  width: 180px;
  padding-left: 5px;
  background-color: #000;
  user-select: none;
}
.my-video-control .video-controls>span{
  cursor: pointer;
  color: #c1c2c6;
  margin: 0 4px 0 13px;
}
.svg-icon{
  width: 0.8em !important;
  height: 0.8em !important;
}

.player-wraper{
  position: absolute;
  left: 0;
  right: 0;
  bottom: 34px;
  top: 0;
  overflow: hidden;
}
.my-video-wrapper{
  float: left;
  position: relative;
  background-image: url(../../../assets/images/bg-video.jpg);
  background-size: 100% 100%;
  background-position: 50%;
}
//.el-form-item{
//  margin-bottom: 9px;
//}
//.el-form--inline .el-form-item{
//  margin-right:0;
//}
//.el-form-item__label{
//  padding: 0 5px 0 0;
//}
.el-form-item--small{
  margin-bottom: 0!important;
  margin-top: 1px!important;
}

.video-button{
  background-color: #e6a23c;
  color: white;
  height: 36px;
  margin-left: 10px
}
.video-select{
  width: 130px;
  margin-left:10px;
  font-size: 12px;
}
.video-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 84px);
}

.video-left-board {
  width: 275px;
  position: absolute;
  left: 0;
  top: 0;
  height: calc(100vh - 84px);
}

.video-left-board-top{
  background-color: #E8EAED;
  position: relative;
  height: 42px;
  //background: #fff;
  border-bottom: 1px solid rgb(214, 214, 214);
  border-right: 1px solid rgb(214, 214, 214);
  box-sizing: border-box;
}

.video-left-board-center{
  border-right: 1px solid rgb(214, 214, 214);
  overflow: auto;
  position: relative;
  height: calc(100vh - 126px);
  background: #fff;
  box-sizing: border-box;
}
/* 设置::-webkit-scrollbar可以让滚动条消失，但仍可以滚动 */
.video-left-board-center::-webkit-scrollbar {
  display:none
}
.video-left-board-down{
  border-right: 1px solid rgb(214, 214, 214);
  overflow: auto;
  position: relative;
  height: 140px;
  background: #dce4ef;
  box-sizing: border-box;
}
/* 设置::-webkit-scrollbar可以让滚动条消失，但仍可以滚动 */
//.video-left-board-down::-webkit-scrollbar {
//  display:none
//}
.video-center-board {
  height: calc(100vh - 84px);
  width: auto;
  margin: 0 300px 0 275px;
  box-sizing: border-box;
}
.video-center-board-top{
  background-color: #E8EAED;
  position: relative;
  height: 42px;
  box-sizing: border-box;;
  border-top: none;
}
.videoCenterBoardDown{
  height: calc(100vh - 84px)!important;
}
.video-right-board {
  width: 300px;
  position: absolute;
  right: 0;
  top: 0;
  height: calc(100vh - 84px);
}
</style>
